package NIO;

import com.sun.deploy.util.SyncFileAccess;

import javax.xml.bind.SchemaOutputResolver;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @leiwenkang 2018-03-01 11:17.
 */
public class TestNIO {
    public static void main(String[] args) throws Exception {

    }


    private void copyFile() throws Exception{
        RandomAccessFile fromFile = new RandomAccessFile("e://1.txt", "rw");
        FileChannel fromChannel = fromFile.getChannel();

        RandomAccessFile toFile = new RandomAccessFile("e://2.txt", "rw");
        FileChannel toChannel = toFile.getChannel();

        long position = 0;
        long count = fromChannel.size();

        fromChannel.transferTo(position, count, toChannel);
    }
    private void writeFile() throws Exception{
        RandomAccessFile toFile = new RandomAccessFile("e://4.txt", "rw");
        FileChannel toChannel = toFile.getChannel();
        String newData = "New String to write to file..." + System.currentTimeMillis();

        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        buf.put(newData.getBytes());

        buf.flip();

        while(buf.hasRemaining()) {
            toChannel.write(buf);
        }

    }


    private void readFile() throws Exception{
        RandomAccessFile accessFile = new RandomAccessFile("e://1.txt", "rw");
        FileChannel inChannle = accessFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(48);
        int bytesRead = inChannle.read(buf);
        while (bytesRead != -1) {
            System.out.println("Read " + bytesRead);
            buf.flip();
            while (buf.hasRemaining()) {
                System.out.println((char)buf.get());
            }
            buf.clear();
            bytesRead = inChannle.read(buf);
        }
        accessFile.close();
    }
}
